import { EventBus } from '@/store/index'
import { COMPONENT_TYPES, CONTROL_TYPES, TIMER_TYPES_MAP } from '@/common/const'
import { convertDateChineseFormat, isJSON, getCompIdByParam, isHasOwnProperty } from '@/plugins/utils'
import { FRONT_EVENT_TYPE_MAPS, STATISTIC_DATA_TYPES_MAP } from '@/common/events'

const intervalFuncCb = {}

export function initNumberDataProcess(numberWbData, compId, componentMap, controls, siteInfo) {
  const compData = componentMap[compId];
  const interactionEvent = compData.events.interactionData;
  const interactionStr = interactionEvent && interactionEvent.comps[0].attrs.value;
  if(interactionStr && isJSON(interactionStr)){
    const interactionObj = JSON.parse(interactionStr);
    let intervalFuncCbKey = intervalFuncCb["oppositNnumberCb-" + compId];
    if(interactionObj && isHasOwnProperty(interactionObj, 'pk') && !intervalFuncCbKey) {
      intervalFuncCbKey = window.setInterval(() => {
        if(siteInfo.isLoading) {
          // 通讯中
        } else {
          changeNumberProcess(numberWbData, interactionObj, componentMap, controls, true);
          EventBus.$emit("refreshDynamicData");
          window.clearInterval(intervalFuncCbKey);
        }
      }, siteInfo.reloadTime)
    }
  }
  numberWbData.num = parseInt(numberWbData.num);
}

function changeNumberProcess(numberWbData, interactionObj, componentMap, controls, isOpposite) {
  let percent = 0;
  const oppositeNumberCompId = interactionObj.pk.oppositeNumberCompId;//oppositeNumberCompId
  const oppositeNumberWbData = controls[oppositeNumberCompId][CONTROL_TYPES.number].data;
  let total = numberWbData.num + oppositeNumberWbData.num;
  if(total == 0) {
    percent = 0;
  } else {
    percent = Math.round(numberWbData.num/total * 100);
  }
  numberWbData.process = percent;

  if(isOpposite) {
    let oppositeCompData = componentMap[oppositeNumberCompId];
    const oppositeInteractionEvent = oppositeCompData.events.interactionData;
    const oppositeInteractionStr = oppositeInteractionEvent.comps[0].attrs.value;
    const oppositeInteractionObj = JSON.parse(oppositeInteractionStr);
    if(interactionObj && isHasOwnProperty(interactionObj, 'pk')) {
      changeNumberProcess(oppositeNumberWbData, oppositeInteractionObj, componentMap, controls, false);
    }
  }
}

export function coverPushCompPic(coverPushCompIds, controls) {
  let elements;
  _.forEach(coverPushCompIds, (compId) => {
    elements = controls[compId][CONTROL_TYPES.wb_push].data.elements;
    _.forEach(elements, (item) => {
      item.pics = []
    })
  })
  coverPushCompIds = {}
}
export function dealStatisticData(statisticDataType, state, compData){
  const statisticData = state.statisticData, allPages = state.allPages, componentMap = state.componentMap;
  //根据文案规则初始化显示隐藏组件，或者设置关联组件的数据
  const ruleStr = compData.events.statisticData.comps[1].attrs.value;
  if(ruleStr && ruleStr.length > 0){
    visibleHiddenCompByRule(ruleStr, statisticData, componentMap);
  }
  //文本组件中数据键值替换
  if(statisticDataType == STATISTIC_DATA_TYPES_MAP.reportPasturePlan){
    //牧场计划
    if(statisticData.info){
      if(_.isArray(statisticData.info.user)){
        statisticData.userName = "哎呀~这个朋友貌似走丢了";
      }else{
        statisticData.userName = statisticData.info.user.name;
      }
      if(statisticData.info.feed){
        if(_.isArray(statisticData.info.feed)){
          statisticData.fashionFeed = "年度最高光博文好像走丢了~";
        }else{
          let timeStr = convertDateChineseFormat(statisticData.info.feed.created_at);
          let text = statisticData.info.feed.text;
          if(text.length > 10){
            text = text.substring(0, 10) + '...';
          }
          statisticData.fashionFeed = timeStr + "\r\n" +  text;
        }
      }else{
        statisticData.fashionFeed = "年度最高光博文好像走丢了~";
      }
    }
    //替换文本中的数据字段为获取的真实数据
    replaceCompText(allPages, statisticData);
  } else if(statisticDataType == STATISTIC_DATA_TYPES_MAP.weibo2020 || statisticDataType == STATISTIC_DATA_TYPES_MAP.xiaomi10Days || statisticDataType == STATISTIC_DATA_TYPES_MAP.xiaomi10Interact
    || statisticDataType == STATISTIC_DATA_TYPES_MAP.weiboTime
    ){
    replaceCompText(allPages, statisticData);
  }

  const relateCompIdStr = compData.events.statisticData.comps[2].attrs.value;
  if(statisticDataType == STATISTIC_DATA_TYPES_MAP.aes){
    //解密数据
    if(relateCompIdStr){
      const relateDatas = JSON.parse(relateCompIdStr);
      _.forEach(relateDatas, (relateData) => {
        if(relateData.relateCompId){
          let code = window.Base64.decode(statisticData);
          const relateCompData = componentMap[relateData.relateCompId];
          if(relateCompData.cid == COMPONENT_TYPES.wb_img){
            intervalFuncCb.JsBarcodeCb = window.setInterval(() => {
              if(window.JsBarcode){
                window.clearInterval(intervalFuncCb.JsBarcodeCb);
                window.JsBarcode("#" + relateCompData.commonAttr.imgId, code, {
                });
                window.setTimeout(() => {
                  let relateEventCompId = getCompIdByParam(compData.commonAttr.relateEventCompId);
                  if(relateEventCompId){
                    EventBus.$emit("itemClick", {id: relateEventCompId, index: 0, e: null, isReset: false});
                  }
                }, 1000)
              }
            }, state.siteInfo.reloadTime);
          }else if(relateCompData.cid == COMPONENT_TYPES.wb_text){
            relateCompData.commonAttr.text = code;
          }
        }
      })
    }
  }else{
    //修改关联组件数据
    if(relateCompIdStr){
      const relateDatas = JSON.parse(relateCompIdStr);
      _.forEach(relateDatas, (relateData) => {
        if(relateData.relateCompId){
          const relateCompData = state.componentMap[relateData.relateCompId];
          if(relateCompData){
            if(relateCompData.cid == COMPONENT_TYPES.wb_img){
              if(relateCompData.lists){
                relateCompData.commonAttr.url = relateCompData.lists[statisticData[relateData.dataAttr]].url;
              }else if(relateCompData.interactionData){
                if(relateCompData.interactionData.isDimension){
                  relateCompData.commonAttr.dataIndex = statisticData[relateData.dataAttr];
                }else{
                  relateCompData.commonAttr.url = relateCompData.interactionData.lists[statisticData[relateData.dataAttr]].url;
                }
              }
            }else if(relateCompData.cid == COMPONENT_TYPES.wb_radio){
              const frontEvent = relateCompData.events.frontEvents;
              const frontEventType = frontEvent && frontEvent.comps[0].attrs.value;
              if(frontEventType == FRONT_EVENT_TYPE_MAPS.changeRelateCompData){
                relateCompData.commonAttr.dataIndex = statisticData[relateData.dataAttr];
              }
            }
          }
        }
      })
    }
  }
}

export function getControlDataActivityInfoTimeData(siteData, componentMap){
  let controlData
  let activityInfo = {}
  let timeData
  for(let compId in siteData.controls){
    let compControls = siteData.controls[compId]
    for(let eventKey in compControls){
      let controlData_ = compControls[eventKey]
      if(controlData_.controlId == CONTROL_TYPES.wb_activity_info){
        controlData = controlData_
        let compData = componentMap[compId];
        _.merge(activityInfo, controlData.data)
        _.forEach(compData.events, (event) => {
          if(event.controlId == eventKey && event.mouseBehavior == 'load' || event.mouseBehavior == 'data'){
            activityInfo.isLoad = true
          }
        })
      }
      if(controlData_.controlId == CONTROL_TYPES.timer && controlData_.data.type == TIMER_TYPES_MAP.activityCountdownTime){
        timeData = { compId:'', data: {} }
        timeData.compId = compId
        timeData.data = controlData_
      }
    }
  }
  return {controlData, activityInfo, timeData}
}
//投票排序
export function sortReposts(controlData, componentData){
  if(!controlData[CONTROL_TYPES.vote] || !componentData){
    return
  }
  const controlId = controlData[CONTROL_TYPES.wb_reposts] ? CONTROL_TYPES.wb_reposts :  CONTROL_TYPES.wb_user
  let lists;
  if(controlData[controlId]){
    lists = controlData[controlId].data.elements
  }else if(componentData.lists && componentData.lists.length > 0){
    lists = componentData.lists
  }

  const voteObj = controlData[CONTROL_TYPES.vote].data.elements
  const isAddReposts = componentData.commonAttr.isAddReposts
  let vote_coefficient = parseInt(controlData[CONTROL_TYPES.vote].data.vote_coefficient);
  if(!vote_coefficient){
    vote_coefficient = 1;
  }
  _.forEach(lists, (item) => {
    const key = item.voteId || item.mid || item.uid 
    if(key){
      let num = voteObj[key] && parseFloat(voteObj[key].num);
      if(num === undefined) {
        num = 0
      }
      item.num = num * vote_coefficient;
      if(item.mid){
        const reposts_count = parseInt(item.reposts_count)
        const comments_count = parseInt(item.comments_count)
        const attitudes_count = parseInt(item.attitudes_count)
        if(isAddReposts){
          item.num = parseInt(reposts_count + comments_count + attitudes_count + num) * vote_coefficient
        }
      }
    }
  })
  if(componentData.commonAttr.isSort){
    const listsSort = _.sortBy(lists, (item) => { return -item.num})
    while(lists.length > 0){
      lists.pop()
    }
    _.forEach(listsSort, (item,index) => {
      if(item.voteId == componentData.commonAttr.pushIndex + 1){
        componentData.commonAttr.itemIndex = index // 更新组件索引
      }
      lists.push(item)
    })
  }
}
export function initComponentMapInPage(componentMap, allPages){
  _.forEach(allPages, (page) => {
    initComponentMap(componentMap, page);
  })
}

function initComponentMap(componentMap, pageOrGroupComponent){
  _.forEach(pageOrGroupComponent.components, (componentData) => {
    componentMap[componentData.id] = componentData;
    if(componentData.components && componentData.components.length > 0){
      if(componentData.conAttr.realTop > 0){
        componentData.conAttr.initTop = componentData.conAttr.top;
      }
      initComponentMap(componentMap, componentData);
    }
  })
}
export function getComponentDataInAllById(searchId, allPages){
  for(let j = 0, len = allPages.length; j < len ; j++){
    let page = allPages[j];
    if(page.id == searchId){
      return page
    }
    let componentData = searchComponentDataById(searchId, page);
    if(componentData){
      return componentData;
    }
  }
  return null;
}
export function searchComponentDataById(searchId, pageOrGroupComponent){
  let components = pageOrGroupComponent.components
  let len = components.length
  for(let i = 0; i < len; i++){
    let componentData = components[i]
    if(componentData.id == searchId){
      return componentData
    }else{
      if(componentData.components && componentData.components.length > 0){
        let compData = searchComponentDataById(searchId, componentData)
        if(compData){
          return compData;
        }
      }
    }
  }
  return null
}
export function searchComponentDataByCid(cid, pageOrGroupComponent){
  let components = pageOrGroupComponent.components
  let len = components.length
  for(let i = 0; i < len; i++){
    let componentData = components[i]
    if(componentData.cid == cid){
      return componentData
    }else{
      if(componentData.components && componentData.components.length > 0){
        let compData = searchComponentDataById(cid, componentData)
        if(compData){
          return compData;
        }
      }
    }
  }
  return null
}
// 找到事件的关联id， 发processFrame事件，刷新树的状态
export function refreshBitmapTextFrame(id, num, controlId, componentMap){
  let componentData = componentMap[id]
  if(!componentData){
    return
  }
  let relevantCompId
  for(let key in componentData.events){
    let event = componentData.events[key]
    if(event.controlId == controlId){
      let params = event.comps[2] && event.comps[2].attrs.value
      if(params && isJSON(params)){
        relevantCompId = JSON.parse(params).relateCompId;
      }
      break
    }
  }
  if(!relevantCompId){
    return
  }
  let relevantComponentData = componentMap[relevantCompId]
  if(!relevantComponentData){
    return
  }
  let processes = JSON.parse(relevantComponentData.commonAttr.processes)
  let index_ = 1
  for(let i = 0, len = processes.length-1; i < len; i++){
    if(num >= processes[i] && num < processes[i+1]){
      index_ = i + 1
      break
    }
  }
  if(num >= processes[processes.length-1]){
    index_ = processes.length
  }
  window.setTimeout(() => {
    EventBus.$emit("processFrame", {frame: index_.toString(), relevantCompId})
  }, 50)
}
export function resetVisibleComponents(visibleComponents, componentMap){
  let data_ = { isVisible: false }
  _.forEach(visibleComponents, (compId) => {
   let componentData = componentMap[compId]
    if(componentData && componentData.id == compId){
      _.merge(componentData.commonAttr, data_)
    }
  })
}
export function resetAllCropImgUrl(pages){
  _.forEach(pages, (page) => {
    resetCropImgUrl(page)
  })
}
export function resetCropImgUrl(pageOrGroupComp){
  _.forEach(pageOrGroupComp.components, (componentData) => {
    if(componentData.cid == COMPONENT_TYPES.group_component || componentData.components && componentData.components.length > 0){
      resetCropImgUrl(componentData)
    }else{
      delete componentData.commonAttr.isLoadedImg
    }
  })
}
export function computeVoteTotal(elements){
  let total = 0
  _.forEach(elements, (item) => {
    total += parseInt(item.num)
  })
  return total
}

export function replaceCompText(allPages, data){
  //找出所有页面中的文本中有需要替换的组件
  for(let j = 0, len = allPages.length; j < len ; j++){
    let page = allPages[j];
    replacePageOrGroupText(page, data);
  }
}

function replacePageOrGroupText(pageOrGroup, data){
  let components = pageOrGroup.components;
  let len = components.length;
  let componentData;
  for(let i = 0; i < len; i++){
    componentData = components[i];
    if(componentData.cid == COMPONENT_TYPES.wb_text){
      replaceTextBydata(componentData.commonAttr, data)
    }else{
      if(componentData.cid == COMPONENT_TYPES.group_component || componentData.components && componentData.components.length > 0){
        replacePageOrGroupText(componentData, data)
      }
    }
  }
}

function replaceTextBydata(commonAttr, data){
  // eslint-disable-next-line
  let dataKeys = commonAttr.text.match(/\$[^\$]+\$/g);
  let value;
  let dataKey_;
  commonAttr.text = commonAttr.text.replace(new RegExp(/\$/, 'g'), '')
  _.forEach(dataKeys, (dataKey) => {
    dataKey_ = dataKey.replace(/\$/g, '');
    value = data[dataKey_];
    if(value){
      if(dataKey_.indexOf('_date') != -1){
        value = convertDateChineseFormat(value, false)
      }
      commonAttr.text = commonAttr.text.replace(new RegExp(dataKey_, 'g'), value)
    }
  })
}

export function visibleHiddenCompByRule(ruleStr, data, componentMap){
  //找出规则中的组件与数据对比后改变组件的显示隐藏属性
  let rules = JSON.parse(ruleStr);
  //牧场计划
  // {
  //   blog_total: { condition: 100, compIds: ["53315817-3365-42e4-b993-14f0b828e6f5", "f2938398-3c14-4290-9251-c771b5c03151"] },
  //   latest_date: { condition: 5, compIds: ["d4734f9d-db6a-4f83-92f6-03fd0e37e597", "e077a49a-f05e-46be-9e05-19611018c4f6"] },
  //
  // }
  //数据包
  // var xx = {"bag_0":{"condition":0,"compIds":["c89e052f-7563-4248-8643-9eab7f1f4326",""]}}

  _.forEach(rules, (val, key) => {
    let rule = val;
    let hiddenId;
    let dataVal = data[key];
    if(_.isNumber(rule.condition)){
      if(key == 'latest_date'){
        let time = new Date(data[key]);
        dataVal = time.getHours();
      }
      if(dataVal > rule.condition){
        hiddenId = rule.compIds[1];
      }else{
        hiddenId = rule.compIds[0];
      }
    }else if(_.isBoolean(rule.condition)){
      if(dataVal && dataVal.length > 0 == rule.condition){
        hiddenId = rule.compIds[1];
      }else{
        hiddenId = rule.compIds[0];
      }
    }
    if(hiddenId){
      let hiddenComponentData = componentMap[hiddenId];
      if(hiddenComponentData){
        hiddenComponentData.commonAttr.isVisible = false;
      }
    }
  })
}
